import { Inject, Injectable } from '@nestjs/common';
import { CreateYingpingfankuiDto } from './dto/create-yingpingfankui.dto';
import { UpdateYingpingfankuiDto } from './dto/update-yingpingfankui.dto';
import { SearchPagesDto } from './dto/search-pages.dto';
import { Repository } from 'typeorm';
import { Yingpingfankui } from './entities/yingpingfankui.entity';
import { UserEntity } from 'src/user/entities/user.entity';
import { BusinessException } from 'src/common/exceptions/business.exception';
import { YingshishipinService } from '../yingshishipin/yingshishipin.service';

@Injectable()
export class YingpingfankuiService {
  constructor(
    @Inject('YINGPINGFANKUI_REPOSITORY')
    private yingpingfankuiRepository: Repository<Yingpingfankui>,
    private readonly yingshishipinService: YingshishipinService,
  ) {}
  async create(
    createYingpingfankuiDto: CreateYingpingfankuiDto,
    user: UserEntity,
  ) {
    const shipin = await this.yingshishipinService.findOne(
      createYingpingfankuiDto.id,
    );
    if (!shipin) {
      throw new BusinessException('视频资源不存在');
    }
    const { pingyu, pingfen } = createYingpingfankuiDto;
    const result = this.yingpingfankuiRepository.create({
      pingfen: pingfen,
      pingyu: pingyu,
      shipin: shipin,
      user: user,
    });

    return this.yingpingfankuiRepository.save(result);
  }

  chart() {
    return this.yingpingfankuiRepository
      .createQueryBuilder('yingping')
      .select('yingping.pingfen', 'pingfen')
      .addSelect('COUNT(*)', 'count')
      .groupBy('yingping.pingfen')
      .getRawMany();
  }

  findAll() {
    return `This action returns all yingpingfankui`;
  }

  findOne(id: number) {
    return `This action returns a #${id} yingpingfankui`;
  }

  async findAllPage(pages: SearchPagesDto) {
    const {
      page = 1,
      limit = 10,
      shipinbianhao,
      shipinmingcheng,
      shipinId,
    } = pages;

    // 1. 计算分页偏移量
    const skip = (page - 1) * limit; // 计算跳过的数据量
    const take = limit;

    const where: Record<string, any> = {};

    if (shipinbianhao) {
      where.shipin = { shipinbianhao: shipinbianhao };
    }
    if (shipinmingcheng) {
      where.shipin = { shipinbianhao: shipinmingcheng };
    }
    if (shipinId) {
      where.shipin = { id: shipinId };
    }

    // 3. 执行分页查询
    const [data, total] = await this.yingpingfankuiRepository.findAndCount({
      where,
      relations: ['shipin', 'user'],
      order: { createTime: 'DESC' }, // 按创建时间倒序
      skip,
      take,
    });

    return {
      list: data,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  update(id: number, updateYingpingfankuiDto: UpdateYingpingfankuiDto) {
    return `This action updates a #${id} yingpingfankui`;
  }

  remove(id: number) {
    return this.yingpingfankuiRepository.delete(id);
  }
}
